﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AmkeniCrossLoginApplication.Data_Access;

namespace Amkeni_Monitoring_Plan
{
    public partial class New_Data : System.Web.UI.Page
    {
        Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
        
        int planID;

        protected void Page_Init(object sender, EventArgs e)
        {
            if (Server.UrlDecode(Request.QueryString["id"]) != null)
            {
                planID = int.Parse(Server.UrlDecode(Request.QueryString["id"]));
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (planID > 0)
                {
                    PopulateEditData(planID);
                    //UpdateBtn.Visible = true;
                }
                /*else
                {
                    SaveBtn.Visible = true;
                }*/

                //if (IndicatorList.SelectedValue.Equals("N/A"))
                //{
                //    ProcessIndicatorTextBox.Enabled = true;
                //}
                //else
                //{
                //    ProcessIndicatorTextBox.Enabled = false;
                //}
            }
        }

        protected void PopulateEditData(int id)
        {
            var editData = (from data in db.monitoring_plan_view
                            where data.monitoring_plan_id == id
                            select new
                            {
                                data.RFP_id,
                                data.ip_id,
                                data.outcome_id,
                                data.outcome_name,
                                data.output_id,
                                data.output_name,
                                data.activity,
                                data.indicator_id,
                                data.indicator_name,
                                data.programme_officer,
                                data.ip_officer,
                                data.year,
                                data.resource_required
                            }).Single();
            /*ThematicAreaList.SelectedValue = editData.outcome_id.ToString();*/

            RFPList.DataBind();
            RFPList.SelectedValue = editData.RFP_id.ToString();

            RFPList_SelectedIndexChanged(this, EventArgs.Empty);
            IPList.DataBind();
            IPList.SelectedValue = editData.ip_id.ToString();

            //OutcomeList.DataBind();
            //OutcomeList.SelectedValue = editData.outcome_id.ToString();
            //OutcomeLabel.Text = editData.outcome_name.Trim();

            var selectedOutputs = from data in db.programme_output
                                  where data.outcome_id == editData.outcome_id
                                  select new { data.output_id };
            //OutputList.DataSource = selectedOutputs.ToList();
            //OutputList.AppendDataBoundItems = false;
            //OutputList.DataBind();
            //OutputList.SelectedValue = editData.output_id.ToString();
            //OutputLabel.Text = editData.output_name.Trim();

            ActivityTextBox.Text = editData.activity;

            var outputIndicators = from data in db.indicators
                                   where data.output_id == editData.output_id.Trim() && data.indicator_type_id == 1
                                   select new { data.indicator_id, data.output_indicator_id };
            //IndicatorList.DataSource = outputIndicators.ToList();
            //IndicatorList.AppendDataBoundItems = false;
            //IndicatorList.DataBind();
            //IndicatorList.SelectedValue = editData.indicator_id.ToString();
            //IndicatorList_SelectedIndexChanged(null, null);

            //if (IndicatorList.SelectedValue == "N/A")
            //{
            //    ProcessIndicatorIdHiddenField.Value = editData.indicator_id.ToString();
            //    ProcessIndicatorTextBox.Text = editData.indicator_name;
            //}

            //BaselineTextBox.Text = editData.baseline;
            //TargetTextBox.Text = editData.target;
            //VerificationTextBox.Text = editData.means_of_verification;
            ProgrammeOfficerTextBox.Text = editData.programme_officer;
            IPOfficerTextBox.Text = editData.ip_officer;

            var years = (from data in db.years
                         where data.year1 == editData.year
                         select new { data.year_id }).FirstOrDefault().year_id.ToString();
            YearList.SelectedValue = years;

            //DataSourceTextBox.Text = editData.data_source;
            //MethodOfCollectionTextBox.Text = editData.method_of_collection;
            //CollectionToolsTextBox.Text = editData.collection_tools;
            ResourceTextBox.Text = editData.resource_required.ToString();
            //AssumptionsTextBox.Text = editData.assumptions_and_risks;

            var frequency = (from data in db.monitoring_data_collection_frequency_connector
                             where data.monitoring_plan_id == id
                             select new
                             {
                                 data.report_period_id
                             });

            FrequencyCheckBoxList.DataBind();

            foreach (var freq in frequency)
            {
                if (frequency != null)
                {
                    List<ListItem> items = FrequencyCheckBoxList.Items.Cast<ListItem>().ToList();
                    foreach (var item in items)
                    {
                        if (item.Value.Trim() == freq.report_period_id.ToString().Trim())
                        {
                            item.Selected = true;
                        }
                    }
                }
            }
        }

        //protected void OutputList_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    string outputID = OutputList.SelectedValue.Trim();

        //    var outputIndicators = from data in db.indicators
        //                           where data.output_id == outputID && data.indicator_type_id == 1
        //                           select new
        //                           {
        //                               data.indicator_id,
        //                               data.output_indicator_id
        //                           };

        //    IndicatorList.DataSource = outputIndicators.ToList();
        //    IndicatorList.DataBind();
        //    IndicatorLabel.Text = string.Empty;
        //    ProcessIndicatorTextBox.Enabled = true;

        //    var outputName = (from data in db.programme_output
        //                      where data.output_id == outputID
        //                      select new { data.name }).FirstOrDefault();
        //    if (outputName == null)
        //    {
        //        OutputLabel.Text = "N/A";
        //    }
        //    else
        //    {
        //        OutputLabel.Text = outputName.name;
        //    }
        //}

        //protected void OutcomeList_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    if (OutcomeList.SelectedValue.Trim() != "N/A")
        //    {
        //        int outcomeID = int.Parse(OutcomeList.SelectedValue.Trim());

        //        var selectedOutputs = from data in db.programme_output
        //                              where data.outcome_id == outcomeID
        //                              select new { data.output_id, data.name };

        //        OutputList.Items.Clear();
        //        OutputList.DataSource = selectedOutputs.ToList();
        //        OutputList.DataBind();
        //        OutputLabel.Text = string.Empty;

        //        IndicatorList.Items.Clear();
        //        IndicatorList.DataSource = null;
        //        IndicatorList.DataBind();
        //        IndicatorLabel.Text = string.Empty;
        //        ProcessIndicatorTextBox.Enabled = true;

        //        var outcomeName = (from data in db.programme_outcome
        //                           where data.outcome_id == outcomeID
        //                           select new { data.name }).FirstOrDefault();
        //        if (outcomeName == null)
        //        {
        //            OutcomeLabel.Text = "N/A";
        //        }
        //        else
        //        {
        //            OutcomeLabel.Text = outcomeName.name;
        //        }
        //    }
        //    else
        //    {
        //        OutputList.Items.Clear();
        //        OutputList.DataSource = null;
        //        OutputList.DataBind();
        //        OutputLabel.Text = string.Empty;

        //        IndicatorList.Items.Clear();
        //        IndicatorList.DataSource = null;
        //        IndicatorList.DataBind();
        //        IndicatorLabel.Text = string.Empty;

        //        OutcomeLabel.Text = "N/A";
        //    }
        //}

        //protected void IndicatorList_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    if (IndicatorList.SelectedValue.Trim() != "N/A")
        //    {
        //        int indicatorID = int.Parse(IndicatorList.SelectedValue.Trim());
        //        var indicatorName = (from data in db.indicators
        //                             where data.indicator_id == indicatorID
        //                             select new { data.name }).FirstOrDefault();
        //        IndicatorLabel.Text = indicatorName.name;
        //        ProcessIndicatorTextBox.Text = string.Empty;
        //        ProcessIndicatorIdHiddenField.Value = null;
        //        ProcessIndicatorTextBox.Enabled = false;
        //    }
        //    else
        //    {
        //        IndicatorLabel.Text = "N/A";
        //        ProcessIndicatorTextBox.Enabled = true;
        //    }
        //}

        protected void RFPList_SelectedIndexChanged(object sender, EventArgs e)
        {
            int Rfp_id = int.Parse(RFPList.SelectedValue.Trim());

            var selectedIPs = from data in db.implementing_partner_metadata
                              where data.RFP_id == Rfp_id
                              select new
                              {
                                  data.implementing_partner.ip_id,
                                  data.implementing_partner.abbreviation
                              };

            IPList.DataSource = selectedIPs.ToList();
            IPList.DataBind();
        }

        /*private int? GetProcessIndicatorId(string processIndicator)
        {
            int? id = null;
            try
            {
                id = (from data in db.indicators
                      where data.indicator_type_id == 2 && data.name.Trim() == processIndicator.Trim()
                      select new
                      {
                          data.indicator_id
                      }).FirstOrDefault().indicator_id;
            }
            catch (NullReferenceException ex)
            {
                return null;
            }
            if (id.HasValue)
            {
                return id.Value;
            }
            else
            {
                return null;
            }
        }*/

        //private void SetProcessIndicatorId(string processIndicator)
        //{
        //    //try
        //    //{
        //    //int id;
        //    var id = (from data in db.indicators
        //                where data.indicator_type_id == 2 && data.name.Trim() == processIndicator.Trim()
        //                select new
        //                {
        //                    data.indicator_id
        //                }).SingleOrDefault();
        //    if (id != null)
        //    {
        //        ProcessIndicatorIdHiddenField.Value = id.indicator_id.ToString().Trim();
        //    }
        //    else if (id == null)
        //    {
        //        ProcessIndicatorIdHiddenField.Value = null;
        //    }
        //    //}
        //    //catch (NullReferenceException ex)
        //    //{
        //    //    return;
        //    //}
        //}

        //protected void ProcessIndicatorTextBox_TextChanged(object sender, EventArgs e)
        //{
        //    /*if (GetProcessIndicatorId(ProcessIndicatorTextBox.Text.Trim()) != null)
        //    {
        //        ProcessIndicatorIdHiddenField.Value = GetProcessIndicatorId(ProcessIndicatorTextBox.Text.Trim()).ToString();
        //    }
        //    else
        //    {
        //        ProcessIndicatorIdHiddenField.Value = null;
        //    }*/
        //    SetProcessIndicatorId(ProcessIndicatorTextBox.Text.Trim());
        //    if (ProcessIndicatorTextBox.Text.Trim() != string.Empty)
        //    {
        //        IndicatorList.Enabled = false;
        //    }
        //    else
        //    {
        //        IndicatorList.Enabled = true;
        //    }
        //}

        protected void SaveBtn_Click(object sender, EventArgs e)
        {
            /*try
            {
                monitoring_plan plan = new monitoring_plan();
                plan.RFP_id = int.Parse(RFPList.SelectedValue.Trim());
                plan.ip_id = int.Parse(IPList.SelectedValue.Trim());
                plan.outcome_id = int.Parse(OutcomeList.SelectedValue.Trim());
                plan.output_id = OutputList.SelectedValue.Trim();
                plan.activity = ActivityTextBox.Text.Trim();

                if (IndicatorList.SelectedValue.Trim() != "N/A")
                {
                    plan.indicator_id = int.Parse(IndicatorList.SelectedValue.Trim());
                }
                //else if (ProcessIndicatorIdHiddenField.Value.tr)

                //plan.baseline = BaselineTextBox.Text.Trim();
                //plan.target = TargetTextBox.Text.Trim();
                //plan.means_of_verification = VerificationTextBox.Text.Trim();
                plan.programme_officer = ProgrammeOfficerTextBox.Text.Trim();
                plan.ip_officer = IPOfficerTextBox.Text.Trim();
                //plan.data_source = DataSourceTextBox.Text.Trim();
                //plan.method_of_collection = MethodOfCollectionTextBox.Text.Trim();
                //plan.collection_tools = CollectionToolsTextBox.Text.Trim();
                decimal resource;
                if (Decimal.TryParse(ResourceTextBox.Text.Trim(), out resource))
                {
                    plan.resource_required = resource;
                }
                //plan.assumptions_and_risks = AssumptionsTextBox.Text.Trim();
                plan.year_id = int.Parse(YearList.SelectedValue.Trim());

                if (ProcessIndicatorTextBox.Text.Trim() != string.Empty)
                {
                    if (ProcessIndicatorIdHiddenField.Value.Trim() != null || ProcessIndicatorIdHiddenField.Value.Trim() != "")
                    {
                        int num;
                        if (int.TryParse(ProcessIndicatorIdHiddenField.Value.Trim(), out num))
                        {
                            plan.indicator_id = int.Parse(ProcessIndicatorIdHiddenField.Value.Trim());
                        }
                        else
                        {
                            indicator newProcessIndicator = new indicator();
                            //Types of Indicators ids
                            //1 => programme output indicator
                            //2 => process indicator
                            newProcessIndicator.indicator_type_id = 2;
                            newProcessIndicator.name = ProcessIndicatorTextBox.Text.Trim();
                            if (OutputList.SelectedValue.Trim() != "N/A")
                            {
                                newProcessIndicator.output_id = OutputList.SelectedValue.Trim();
                            }
                            db.indicators.Add(newProcessIndicator);
                            plan.indicator = newProcessIndicator;
                        }
                    }
                }

                db.monitoring_plan.Add(plan);
                //=============================Frequency of Collection===================================================================
                List<ListItem> items = FrequencyCheckBoxList.Items.Cast<ListItem>().Where(n => n.Selected).ToList();
                foreach (var item in items)
                {
                    monitoring_data_collection_frequency_connector freq = new monitoring_data_collection_frequency_connector();
                    //===Add the Object itself to the Primary Table===
                    freq.monitoring_plan = plan;
                    freq.report_period_id = int.Parse(item.Value.Trim());

                    db.monitoring_data_collection_frequency_connector.Add(freq);

                    //=====Works just as well as above=====
                    //db.monitoring_data_collection_frequency_connector.Add(new monitoring_data_collection_frequency_connector()
                    //{
                    //    monitoring_plan = plan,
                    //    report_period_id = int.Parse(item.Value.Trim())
                    //});
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                db.SaveChanges();
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success", "alert('Data Has been saved')", true);
            }*/
        }

        protected void IPList_DataBound(object sender, EventArgs e)
        {
            DropDownList ddl = sender as DropDownList;
            int x;
            if (ddl != null)
            {
                foreach (ListItem li in ddl.Items)
                {
                    if (int.TryParse(li.Value.Trim(), out x))
                    {
                        int id = int.Parse(li.Value.Trim());
                        string name = (from data in db.implementing_partner
                                       where data.ip_id == id
                                       select data.name).FirstOrDefault();
                        li.Attributes["title"] = name;
                    }
                }
            }
        }

        //protected void OutcomeList_DataBound(object sender, EventArgs e)
        //{
        //    DropDownList ddl = sender as DropDownList;
        //    int x;
        //    if (ddl != null)
        //    {
        //        foreach (ListItem li in ddl.Items)
        //        {
        //            if (int.TryParse(li.Value.Trim(), out x))
        //            {
        //                int id = int.Parse(li.Value.Trim());
        //                string name = (from data in db.programme_outcome
        //                               where data.outcome_id == id
        //                               select data.name).FirstOrDefault();
        //                li.Attributes["title"] = name;
        //            }
        //        }
        //    }
        //    ddl.Items.Insert(0, new ListItem("N/A", "N/A"));
        //    ddl.SelectedIndex = 0;
        //}

        //protected void OutputList_DataBound(object sender, EventArgs e)
        //{
        //    DropDownList ddl = sender as DropDownList;
        //    if (ddl != null)
        //    {
        //        foreach (ListItem li in ddl.Items)
        //        {
        //            string id = li.Value.Trim();
        //            string name = (from data in db.programme_output
        //                           where data.output_id == id
        //                           select data.name).FirstOrDefault();
        //            li.Attributes["title"] = name;
        //        }
        //    }
        //    ddl.Items.Insert(0, new ListItem("N/A", "N/A"));
        //    ddl.SelectedIndex = 0;
        //}

        //protected void IndicatorList_DataBound(object sender, EventArgs e)
        //{
        //    DropDownList ddl = sender as DropDownList;
        //    if (ddl != null)
        //    {
        //        foreach (ListItem li in ddl.Items)
        //        {
        //            int id = int.Parse(li.Value.Trim());
        //            string name = (from data in db.indicators
        //                           where data.indicator_id == id
        //                           select data.name).FirstOrDefault();
        //            li.Attributes["title"] = name;
        //        }
        //    }
        //    ddl.Items.Insert(0, new ListItem("N/A", "N/A"));
        //    ddl.SelectedIndex = 0;
        //}
        
        //protected void IndicatorCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
        //{
        //    if ((IndicatorList.SelectedValue == "N/A" && ProcessIndicatorTextBox.Text.Trim() == string.Empty)
        //        || (IndicatorList.SelectedValue != "N/A" && ProcessIndicatorTextBox.Text.Trim() != string.Empty))
        //    {
        //        args.IsValid = false;
        //    }
        //    else
        //    {

        //    }
        //}

        protected void CancelBtn_Click(object sender, EventArgs e)
        {
            mp1.Hide();
            
        }

        protected void CancelActivityBtn_Click(object sender, EventArgs e)
        {
            //Delete any activity without an indicator
            /*Or do something awesome here*/
            //Return to the workplan page
        }

        protected void AddIndicatorBtn_Click(object sender, EventArgs e)
        {            
            monitoring_plan plan = new monitoring_plan();
            try
            {
                plan.RFP_id = int.Parse(RFPList.SelectedValue.Trim());
                plan.ip_id = int.Parse(IPList.SelectedValue.Trim());
                plan.activity = ActivityTextBox.Text.Trim();
                plan.programme_officer = ProgrammeOfficerTextBox.Text.Trim();
                plan.ip_officer = IPOfficerTextBox.Text.Trim();
                plan.year_id = int.Parse(YearList.SelectedValue.Trim());

                decimal resource;
                if (Decimal.TryParse(ResourceTextBox.Text.Trim(), out resource))
                {
                    plan.resource_required = resource;
                }

                
                //=============================Frequency of Collection===================================================================
                List<ListItem> items = FrequencyCheckBoxList.Items.Cast<ListItem>().Where(n => n.Selected).ToList();
                foreach (var item in items)
                {
                    monitoring_data_collection_frequency_connector freq = new monitoring_data_collection_frequency_connector();
                    //===Add the Object itself to the Primary Table===
                    freq.monitoring_plan = plan;
                    freq.report_period_id = int.Parse(item.Value.Trim());

                    db.monitoring_data_collection_frequency_connector.Add(freq);

                    //=====Works just as well as above=====
                    /*db.monitoring_data_collection_frequency_connector.Add(new monitoring_data_collection_frequency_connector()
                    {
                        monitoring_plan = plan,
                        report_period_id = int.Parse(item.Value.Trim())
                    });*/
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (Page.IsValid && (IndicatorValue.Value == string.Empty || IndicatorValue.Value == ""))
                {
                    db.monitoring_plan.Add(plan);
                    db.SaveChanges();

                    string redirectLink = "AddNewIndicatorToActivity.aspx?activity=" + plan.monitoring_plan_id.ToString();

                    Response.Redirect(redirectLink, true);
                }

                //IndicatorValue.Value = plan.monitoring_plan_id.ToString();
                //_planID = plan.monitoring_plan_id;
                //mp1.Show();
            }

            
        }
    }
}